package alert

import (
	"fmt"
	"sync"

	"github.com/go-gomail/gomail"
	"goserver/internal/logger"
)

type AlertConfig struct {
	SMTPHost     string
	SMTPPort     int
	SMTPUser     string
	SMTPPassword string
	FromEmail    string
	ToEmails     []string
}

type AlertManager struct {
	config AlertConfig
	dialer *gomail.Dialer
	mu     sync.Mutex
}

var (
	manager *AlertManager
	once    sync.Once
)

// 初始化告警管理器
func InitAlertManager(config AlertConfig) {
	once.Do(func() {
		manager = &AlertManager{
			config: config,
			dialer: gomail.NewDialer(
				config.SMTPHost,
				config.SMTPPort,
				config.SMTPUser,
				config.SMTPPassword,
			),
		}
	})
}

// 发送告警
func SendAlert(level, title, content string) error {
	if manager == nil {
		return fmt.Errorf("alert manager not initialized")
	}

	manager.mu.Lock()
	defer manager.mu.Unlock()

	m := gomail.NewMessage()
	m.SetHeader("From", manager.config.FromEmail)
	m.SetHeader("To", manager.config.ToEmails...)
	m.SetHeader("Subject", fmt.Sprintf("[%s] %s", level, title))
	m.SetBody("text/html", content)

	if err := manager.dialer.DialAndSend(m); err != nil {
		logger.Log.WithError(err).Error("Failed to send alert email")
		return err
	}

	return nil
}

// 发送错误告警
func SendErrorAlert(title string, err error) {
	content := fmt.Sprintf(`
		<h3>错误详情</h3>
		<p>%v</p>
	`, err)

	if sendErr := SendAlert("ERROR", title, content); sendErr != nil {
		logger.Log.WithError(sendErr).Error("Failed to send error alert")
	}
}

// 发送警告告警
func SendWarningAlert(title, message string) {
	content := fmt.Sprintf(`
		<h3>警告详情</h3>
		<p>%s</p>
	`, message)

	if err := SendAlert("WARNING", title, content); err != nil {
		logger.Log.WithError(err).Error("Failed to send warning alert")
	}
}

// 发送系统告警
func SendSystemAlert(title string, metrics map[string]interface{}) {
	content := "<h3>系统指标</h3><ul>"
	for k, v := range metrics {
		content += fmt.Sprintf("<li>%s: %v</li>", k, v)
	}
	content += "</ul>"

	if err := SendAlert("SYSTEM", title, content); err != nil {
		logger.Log.WithError(err).Error("Failed to send system alert")
	}
} 